#include "esp_err.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <string.h>

#include "rc522.h"

#include <stdio.h>
static const char *TAG = "test";

static void monitor_task(void *arg)
{
	rc522_err_t r;

	struct rc522_tag tag;
	uint8_t key_A[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
	// uint8_t data[16] = "this is test!!!\0";
	uint8_t data[16] = { 0 };
	while (1) // 任务都是一个无限循环，不能返回
	{
		printf("\e[1;1H\e[2J");
		r = rc522_scan(&tag);
		printf("scan state: %d\n", r);

		printf("\nsn: %02x%02x%02x%02x\n", tag.tag_serial_num[0],
		       tag.tag_serial_num[1], tag.tag_serial_num[2],
		       tag.tag_serial_num[3]);
		printf("tag type: %02x%02x\n", tag.tag_type[0],
		       tag.tag_type[1]);

		// r = rc522_write(&tag, key_A, 4, data);
		// printf("write state: %d\n", r);
		r = rc522_read(&tag, key_A, 4, data);
		printf("read state: %d\n", r);

		for (int i = 0; i < 16; i++) {
			if (i % 4 == 0)
				puts("");
			printf("%02x ", data[i]);
		}
		puts("");

		vTaskDelay(500 / portTICK_PERIOD_MS); // 100ms
	}
}

/**@brief Application main function.
 */
void app_main(void)
{
	ESP_ERROR_CHECK(nvs_flash_init());

	rc522_init();

	/*-------------------------- 创建线程 ---------------------------*/
	xTaskCreate(monitor_task, "monitor_task", 2048, NULL, 4, NULL);
}

// ESP_LOGI(TAG, "reg: %02x" ,readRawRc(Status1Reg));
// ESP_LOGI(TAG, "reg: %02x" ,readRawRc(Status2Reg));
// ESP_LOGI(TAG, "reg: %02x" ,readRawRc(WaterLevelReg));
